/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.academik.controller;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import org.academik.model.Anioescolar;
import org.academik.util.FacesUtil;
import org.academik.util.HibernateUtil;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.StatelessSession;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author Javier
 */
@ManagedBean(name = "anioEscolar")
@ViewScoped
public class anioEscolar extends AbstractViewScopedBean implements Serializable {

    /*Declaracion de Variables*/
    private Anioescolar anio;
    private ArrayList<Anioescolar> aniosEscolares;
    private Anioescolar selectedAnio;
    private String url;

    /** Creates a new instance of anioEscolar */
    public anioEscolar() {
        this.nuevo();
    }

    /** Metodos implementados de la clase abstracta 
    Crear: Inserta nuevo registro en la BD*/
    @Override
    public void crear() {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = null;
        try {
            tx = (Transaction) session.beginTransaction();
            if (this.anio.isBoEstado()) {
                String sql = "UPDATE anioescolar a "
                        + "SET a.boEstado=false";
                session.createSQLQuery(sql).executeUpdate();
            }
            session.saveOrUpdate(this.anio);
            session.flush();
            session.clear();
            tx.commit();
            this.nuevo();
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_INFO, "Información:", "El año se creo satisfactoriamente"));
        } catch (HibernateException e) {
            tx.rollback();
            FacesUtil.hibernateException(e);
        } finally {
            session.close();
        }
    }

    /** Eliminar: Elimina el registro seleccionado por el usuario*/
    @Override
    public void eliminar() {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = null;
        //String id = FacesUtil.getRequestParameter("idAnioEscolar");
        //System.out.print(id);
        Anioescolar s = (Anioescolar) session.load(Anioescolar.class, this.selectedAnio.getIdAnioEscolar());
        try {
            tx = (Transaction) session.beginTransaction();
            session.delete(s);
            session.flush();
            session.clear();
            tx.commit();
            this.nuevo();
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Información:", "Registro eliminado satisfactoriamente"));
        } catch (HibernateException e) {
            tx.rollback();
            FacesUtil.hibernateException(e);
        } finally {
            session.close();
        }
    }

    public void imprimir() {
        String bean = (String) UIComponent.getCurrentComponent(FacesContext.getCurrentInstance()).getAttributes().get("informe");
        String contextPath = FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath();
        this.url = contextPath + "/faces/createReportServlet?fileName=";
        String fileName = "";
        String tipo = "application/pdf";
        if ("consolidado".equals(bean)) {
            fileName = "consolidadoMatricula";
        } else if ("ingresos".equals(bean)) {
            fileName = "ingresosDiarios";
        }
        String params = "&tipo=" + tipo + "&anio=" + this.selectedAnio.getNuAnio();
        this.url = this.url + fileName + params;
    }

    @Override
    public void cargarOpciones() {
    }

    @Override
    public void cargarOpciones(int id) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void buscar() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void modificar() {
        this.anio = this.selectedAnio;
    }

    @Override
    public void cargarResgistros() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    /** Método para Inicializar Variables*/
    public void nuevo() {
        this.anio = new Anioescolar();
        this.aniosEscolares = new ArrayList<Anioescolar>();
        this.selectedAnio = null;
        this.populateAnios();
    }

    /** Muestra los datos de la BD en la tabla*/
    public void populateAnios() {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Criteria cAnio = session.createCriteria(Anioescolar.class);
        cAnio.addOrder(Order.asc("nuAnio"));
        this.aniosEscolares = (ArrayList<Anioescolar>) cAnio.list();
        session.close();
    }

    /** Extraer que año se encuentra como lectivo en la BD*/
    public Anioescolar anioLectivo() {
        Anioescolar tempAnio = new Anioescolar();
        Session session = HibernateUtil.getSessionFactory().openSession();
        Criteria cAnioLectivo = session.createCriteria(Anioescolar.class);
        cAnioLectivo.add(Restrictions.eq("boEstado", true));
        tempAnio = (Anioescolar) cAnioLectivo.uniqueResult();
        session.close();
        return tempAnio;
    }

    public ArrayList<SelectItem> cargarAnios() {
        ArrayList<SelectItem> lista = new ArrayList<SelectItem>();
        StatelessSession session = HibernateUtil.getSessionFactory().openStatelessSession();
        String sql = "SELECT a.idAnioEscolar, a.nuAnio "
                + "FROM anioescolar a "
                + "ORDER BY a.nuAnio ASC";
        Query hQuery = session.createSQLQuery(sql);
        Iterator iter = hQuery.list().iterator();
        while (iter.hasNext()) {
            Object[] obj = (Object[]) iter.next();
            lista.add(new SelectItem(obj[0], obj[1].toString(), ""));
        }
        session.close();
        return lista;
    }

    /** Convierte Date a String*/
    public String getStringDate(Date d) {
        return FacesUtil.getStringDate(d);
    }

    /**Getters & Setters*/
    public Anioescolar getAnio() {
        return anio;
    }

    public void setAnio(Anioescolar anio) {
        this.anio = anio;
    }

    public ArrayList<Anioescolar> getAniosEscolares() {
        return aniosEscolares;
    }

    public void setAniosEscolares(ArrayList<Anioescolar> aniosEscolares) {
        this.aniosEscolares = aniosEscolares;
    }

    public Anioescolar getSelectedAnio() {
        return selectedAnio;
    }

    public void setSelectedAnio(Anioescolar selectedAnio) {
        this.selectedAnio = selectedAnio;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}
